package com.dyoud.api.user.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import com.dyoud.user.api.requests.LoginRequest;
import com.dyoud.user.api.requests.RegisterRequest;
import com.dyoud.user.api.response.JuheIdentifireInfoResponse;

import org.douyoudian.utils.ReplaceStarUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.dyoud.api.ReturnInfo;
import com.dyoud.api.exception.ApiExcepiton;
import com.dyoud.api.user.dto.AddBankInfoWithSettingsPayPasswordDto;
import com.dyoud.api.user.dto.BankAddDto;
import com.dyoud.api.user.dto.BankInfoDto;
import com.dyoud.api.user.dto.CheckBankInfoDto;
import com.dyoud.api.user.dto.RegRequestDto;
import com.dyoud.api.user.dto.UnbindBankInfoDto;
import com.dyoud.api.user.dto.UpdateAvatarDto;
import com.dyoud.api.user.dto.UpdateEmailDto;
import com.dyoud.api.user.dto.UpdateNicknameDto;
import com.dyoud.api.user.dto.UpdatePasswordDto;
import com.dyoud.api.user.dto.UpdatePayPasswordDto;
import com.dyoud.api.user.dto.UpdatePhoneDto;
import com.dyoud.api.user.dto.UserInfoDto;
import com.dyoud.api.user.service.BankApiService;
import com.dyoud.api.user.service.UserApiService;
import com.dyoud.core.ResponseBean;
import com.dyoud.user.api.enums.BankTypeEnum;
import com.dyoud.user.api.exception.BankException;
import com.dyoud.user.api.exception.UserException;
import com.dyoud.user.api.model.User;

/**
 * 用户控制器
 * 
 * @author Jonathan
 * @date 2018/03/01
 *
 */
@RestController
@RequestMapping("users")
public class UserController {

    @Resource
    private UserApiService userApiService;

    @Resource
    private BankApiService bankApiService;

    @Value("${pic_prefix}")
    private String picPrefix;

    /**
     * 用户注册
     *
     * @param request
     */

    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseBean register(@RequestBody @Validated RegRequestDto request) {
        ResponseBean response = new ResponseBean();
        try {
            userApiService.register(request);
            response.success();
        } catch (DuplicateKeyException e) {
        }
        return response;
    }

    /**
     * 用户登录
     *
     * @param request
     * @return
     */

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean login(@RequestBody LoginRequest request) {
        UserInfoDto userInfoDto = userApiService.login(request);
        if (userInfoDto == null) {
            return new ResponseBean().fail(ReturnInfo.LOGIN_ERROR_CODE, ReturnInfo.LOGIN_ERROR_MSG);
        }
        String phone = userInfoDto.getPhone();
        phone = ReplaceStarUtils.replaceStar(phone, 4, phone.length() - 4);
        userInfoDto.setPhone(phone);

        return new ResponseBean().success(userInfoDto);
    }

    /**
     * 查询所有用户信息
     * 
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseBean listUser() {
        return new ResponseBean();
    }

    /**
     * 查询单个用户信息
     * 
     * @return
     */
    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    public ResponseBean get(@PathVariable("userId") Long userId) {
        UserInfoDto userInfoDto = userApiService.getUserInfo(userId);
        return new ResponseBean().success(userInfoDto);
    }

    /**
     * 查询用户信息
     * 
     * @return
     */
    @RequestMapping(value = "/{userId}/nickname", method = RequestMethod.PUT)
    public ResponseBean updateNickname(@PathVariable("userId") Long userId, @RequestBody UpdateNicknameDto nicknameDto) {
        nicknameDto.setUserId(userId);
        boolean isOk = userApiService.updateNickname(nicknameDto);
        if (!isOk) {
            return new ResponseBean().fail(ReturnInfo.UPDATE_NICKNAME_CODE, ReturnInfo.UPDATE_NICKNAME_MSG);
        }
        return new ResponseBean().success(nicknameDto.getNickname());
    }

    /**
     * 修改用户提现密码
     * 
     * @return
     */
    @RequestMapping(value = "/{userId}/payPasword", method = RequestMethod.PUT)
    public ResponseBean updatePayPassword(@PathVariable("userId") Long userId, @RequestBody UpdatePayPasswordDto passwordDto) {
        passwordDto.setUserId(userId);
        ResponseBean response = new ResponseBean();
        boolean isOk = false;

        try {
            isOk = userApiService.updatePayPassword(passwordDto);
        } catch (UserException e) {
            response.fail(e.getMessage());
        }
        if (!isOk) {
            return response.fail(ReturnInfo.CHANAGE_PAY_PASSWORD_FAIL_CODE, ReturnInfo.CHANAGE_PAY_PASSWORD_FAIL_MSG);
        }
        return response.success();
    }

    /**
     * 修改用户邮箱
     * 
     * @return
     */
    @RequestMapping(value = "/{userId}/email", method = RequestMethod.PUT)
    public ResponseBean updateEmail(@PathVariable("userId") Long userId, @RequestBody @Validated UpdateEmailDto emailDto) {
        emailDto.setUserId(userId);
        boolean isOk = userApiService.updateEmail(emailDto);
        if (!isOk) {
            return new ResponseBean().fail(ReturnInfo.UPDATE_EMAIL_CODE, ReturnInfo.UPDATE_EMAIL_MSG);
        }
        return new ResponseBean().success(emailDto.getEmail());
    }

    /**
     * 修改用户头像
     * 
     * @return
     */
    @RequestMapping(value = "/{userId}/avatar", method = RequestMethod.PUT)
    public ResponseBean updateEmail(@PathVariable("userId") Long userId, @RequestBody @Validated UpdateAvatarDto avatarDto) {
        avatarDto.setUserId(userId);
        boolean isOk = userApiService.updateAvatar(avatarDto);
        if (!isOk) {
            return new ResponseBean().fail(ReturnInfo.UPDATE_AVATAR_CODE, ReturnInfo.UPDATE_AVATAR_MSG);
        }
        return new ResponseBean().success(avatarDto.getAvatar());
    }

    /**
     * 修改用户手机号
     * 
     * @return
     */
    @RequestMapping(value = "/{userId}/phone", method = RequestMethod.PUT)
    public ResponseBean updatePhone(@PathVariable("userId") Long userId, @RequestBody UpdatePhoneDto phoneDto) {
        phoneDto.setUserId(userId);
        ResponseBean response = new ResponseBean();
        try {
            boolean isOk = userApiService.updatePhone(phoneDto);
            if (!isOk) {
                return response.fail(ReturnInfo.UPDATE_PHONE_CODE, ReturnInfo.UPDATE_PHONE_MSG);
            }
            response.success(phoneDto.getPhone());
        } catch (ApiExcepiton e) {
            response.fail(ReturnInfo.SMS_CODE, ReturnInfo.SMS_MSG);

        }
        return response;
    }

    /**
     * 修改用户密码
     * 
     * @return
     */
    @RequestMapping(value = "/{userId}/credential", method = RequestMethod.PUT)
    public ResponseBean updatePassword(@PathVariable("userId") Long userId, @RequestBody UpdatePasswordDto passwordDto) {
        passwordDto.setUserId(userId);
        ResponseBean response = new ResponseBean();
        boolean isOk = userApiService.updatePassword(passwordDto);
        if (!isOk) {
            return response.fail(ReturnInfo.UPDATE_PASSWORD_CODE, ReturnInfo.UPDATE_PASSWORD_MSG);
        }
        return response.success();
    }

    /**
     * 查询银行卡
     * 
     * @return
     */
    @RequestMapping(value = "/{userId}/bankInfo", method = RequestMethod.GET)
    public ResponseBean updatePassword(@PathVariable("userId") Long userId) {
        ResponseBean response = new ResponseBean();
        List<BankInfoDto> banks = bankApiService.listBanks(userId);
        return response.success(banks);
    }

    /**
     * 添加银行卡
     * 
     * @return
     */
    @RequestMapping(value = "/{userId}/bankInfo", method = RequestMethod.POST)
    public ResponseBean addBankInfo(@PathVariable("userId") Long userId, @RequestBody @Validated BankAddDto addDto) {
        ResponseBean response = new ResponseBean();

        try {
            boolean isOk = bankApiService.addBank(addDto);
            if (!isOk) {
                response.fail(ReturnInfo.ADD_BANK_CODE, ReturnInfo.ADD_BANK_MSG);
            }
            response.success();
        } catch (ApiExcepiton e) {
            response.fail(ReturnInfo.SMS_INVALID_CODE, ReturnInfo.SMS_INVALID_MSG);
        } catch (BankException e) {
            response.fail(ReturnInfo.ADD_BANK_MAX_CODE, ReturnInfo.ADD_BANK_MAX_MSG);
        }

        return response;
    }

    /**
     * 获取银行卡
     * 
     * @return
     */
    @RequestMapping(value = "/{userId}/simpleBankInfo", method = RequestMethod.GET)
    public ResponseBean getBankInfo(@PathVariable("userId") Long userId, @RequestParam("bankId") Long bankId) {
        ResponseBean response = new ResponseBean();

        try {
            BankInfoDto bankInfoDto = bankApiService.getByUserId(userId, bankId);
            response.success(bankInfoDto);
        } catch (BankException e) {
            response.fail(ReturnInfo.BANK_NOT_EXISTS_CODE, ReturnInfo.BANK_NOT_EXISTS_MSG);
        }

        return response;
    }

    /**
     * 是否绑定手机号
     * 
     * @param userId
     * @return
     */
    @RequestMapping(value = "/{userId}/phone", method = RequestMethod.GET)
    public ResponseBean isBindPhone(@PathVariable("userId") Long userId) {
        UserInfoDto dto = userApiService.getUserInfo(userId);
        if (dto == null || dto.getUserId() == null) {
            return new ResponseBean().fail(ReturnInfo.USER_NULL_CODE, ReturnInfo.USER_NULL_MSG);
        }
        return new ResponseBean().success(userApiService.isBindPhone(userId));
    }

    /**
     * 绑定手机号
     * 
     * @param userId
     * @param phone
     * @return
     */

    @RequestMapping(value = "/{userId}/phone", method = RequestMethod.POST)
    public ResponseBean bindPhone(@PathVariable("userId") Long userId, @RequestParam("phone") String phone) {
        UserInfoDto dto = userApiService.getUserInfo(userId);
        if (dto == null || dto.getUserId() == null) {
            return new ResponseBean().fail(ReturnInfo.USER_NULL_CODE, ReturnInfo.USER_NULL_MSG);
        }
        if (!userApiService.bindPhone(userId, phone)) {
            return new ResponseBean().fail(ReturnInfo.BIND_PHONE_CODE, ReturnInfo.BIND_PHONE_MSG);
        }
        return new ResponseBean().success();
    }

    /**
     * 解绑银行卡
     * 
     * @param checkBankInfoDto
     * @return
     */
    @RequestMapping(value = "/{userId}/unbindBankInfo", method = RequestMethod.PUT)
    public ResponseBean unbindBankInfo(@PathVariable("userId") Long userId, @RequestBody @Validated UnbindBankInfoDto unbindBankInfoDto) {
        unbindBankInfoDto.setUserId(userId);
        ResponseBean response = new ResponseBean();
        try {
            bankApiService.unBindBankInfo(unbindBankInfoDto);
            response.success();
        } catch (UserException e) {
            response.fail(e.getMessage());
        }
        return response;
    }

    /**
     * 添加并修改用户支付密码
     * 
     * @param checkBankInfoDto
     * @return
     */
    @RequestMapping(value = "/{userId}/addBankInfoWithSettingsPayPassword", method = RequestMethod.PUT)
    public ResponseBean addBankInfoWithSettingsPayPassword(@PathVariable("userId") Long userId,
            @RequestBody @Validated AddBankInfoWithSettingsPayPasswordDto addBankInfoWithSettingsPayPassword) {
        addBankInfoWithSettingsPayPassword.setUserId(userId);
        addBankInfoWithSettingsPayPassword.setType(BankTypeEnum.SAVING_CARD.getValue());
        ResponseBean response = new ResponseBean();
        try {
            userApiService.addBankInfoWithSettingsPayPassword(addBankInfoWithSettingsPayPassword);
            response.success();
        } catch (UserException e) {
            response.fail(e.getMessage());
        }
        return response;
    }

}
